package oa.hleast.xswl.controller.oauth;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.wx.config.WeAppConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Slf4j
@AllArgsConstructor
@RequestMapping("/wxauth/{appId}")
@RestController
public class WxPortalController {
    @Autowired
    private WeAppConfig weAppConfig;

    /**  验证消息 https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Access_Overview.html **/
    @GetMapping(produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable String appId,
                          @RequestParam(name = "signature", required = false) String signature,
                          @RequestParam(name = "timestamp", required = false) String timestamp,
                          @RequestParam(name = "nonce", required = false) String nonce,
                          @RequestParam(name = "echostr", required = false) String echostr) {
        log.info("\n"+appId+"接收到来自微信服务器的认证消息：signature = " + signature + ", timestamp = " + timestamp + ", nonce = " + nonce + ", echostr = " + echostr);

        if (StrUtil.hasBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }


        final WxMaService wxService = weAppConfig.getWxMaService(appId);

        if (wxService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }

        return "非法请求";
    }

    /** 事件推送 https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Receiving_event_pushes.html **/
    @PostMapping(produces = "application/xml; charset=UTF-8")
    public String authPost(@PathVariable String appId,
                       @RequestBody String requestBody,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature,
                       @RequestParam(name = "encrypt_type", required = false) String encryptType,
                       @RequestParam(name = "signature", required = false) String signature,
                       @RequestParam("timestamp") String timestamp,
                       @RequestParam("nonce") String nonce) {
        log.info("\n"+appId+"接收微信请求：[msg_signature=" + msgSignature + ", encrypt_type=" + encryptType + ", signature=" + signature + "," +
                " timestamp=" + timestamp + ", nonce=" + nonce + ", requestBody=" + requestBody);

//        final WxMaService wxService = weAppConfig.getWxMaService(appid);
//
//        final boolean isJson = Objects.equals(wxService.getWxMaConfig().getMsgDataFormat(),
//                WxMaConstants.MsgDataFormat.JSON);
//        if (StrUtil.isBlank(encryptType)) {
//            // 明文传输的消息
//            WxMaMessage inMessage;
//            if (isJson) {
//                inMessage = WxMaMessage.fromJson(requestBody);
//            } else {//xml
//                inMessage = WxMaMessage.fromXml(requestBody);
//            }
//
//            this.route(inMessage, appid);
//            return "success";
//        }
//
//        if ("aes".equals(encryptType)) {
//            // 是aes加密的消息
//            WxMaMessage inMessage;
//            if (isJson) {
//                inMessage = WxMaMessage.fromEncryptedJson(requestBody, wxService.getWxMaConfig());
//            } else {//xml
//                inMessage = WxMaMessage.fromEncryptedXml(requestBody, wxService.getWxMaConfig(),
//                        timestamp, nonce, msgSignature);
//            }
//
//            this.route(inMessage, appid);
        return "success";
    }

//    private void route(WxMaMessage message, String appid) {
//        try {
//            WxMaConfiguration.getRouter(appid).route(message);
//        } catch (Exception e) {
//            this.logger.error(e.getMessage(), e);
//        }
//    }
}
